package com.frxuexi.mynews.fragment

import android.content.Context
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.frxuexi.lib_commom.GlideUtils
import com.frxuexi.mynews.adapter.MyNewsAdapter
import com.frxuexi.mynews.databinding.FragmentHomeBinding
import com.frxuexi.mynews.entity.NewsTypeEntity
import com.frxuexi.mynews.intent.NewsIntent
import com.frxuexi.mynews.intent.NewsTypeIntent
import com.frxuexi.mynews.state.NewsState
import com.frxuexi.mynews.state.NewsTypeState
import com.frxuexi.mynews.viewmodel.NewsTypeViewModel
import com.frxuexi.mynews.viewmodel.NewsViewModel
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayout.OnTabSelectedListener
import com.youth.banner.loader.ImageLoader
import kotlinx.coroutines.launch


class HomeFragment : Fragment() {
    lateinit var vm:NewsTypeViewModel
    lateinit var db:FragmentHomeBinding
    lateinit var list: ArrayList<NewsTypeEntity>
    lateinit var vm2:NewsViewModel
    lateinit var newsAdapter: MyNewsAdapter

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        db=FragmentHomeBinding.inflate(layoutInflater,container,false)
        // Inflate the layout for this fragment
//        val view = inflater.inflate(R.layout.fragment_home, container, false)

        vm=ViewModelProvider(this).get(NewsTypeViewModel::class.java)
        vm2=ViewModelProvider(this).get(NewsViewModel::class.java)

        newsAdapter= MyNewsAdapter()
        db.homeRv.apply {
            adapter=newsAdapter
            layoutManager=LinearLayoutManager(context)
        }

        newsAdapter.setOnItemClickListener { adapter, view, position ->
            val id = newsAdapter.data.get(position).id
            Log.i("===a",id.toString())
            ARouter.getInstance().build("/app/DetailActivity").withString("id",id.toString()).navigation()
//            ARouter.getInstance().build("/app/DetailWebActivity").withString("id",id.toString()).navigation()
//            ARouter.getInstance().build("/app/VideoActivity").withString("id",id.toString()).navigation()
        }

        db.homeTab.setOnTabSelectedListener(object :OnTabSelectedListener{
            override fun onTabSelected(tab: TabLayout.Tab?) {
                newsAdapter.data.clear()
                Log.i("===po",tab?.position.toString())
                if(list.size==0){
                    return
                }
                //选择的分类id
                tab?.position?.let {
                    val id = list.get(it).id
                    lifecycleScope.launch {
                        vm2.channel.send(NewsIntent.getNews(1,id))
                    }
                }

            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })

        //类型列表数据
        lifecycleScope.launch {
            vm.newsState.collect{
                when(it){
                    is NewsTypeState.onSucess->
                    {
                        list=ArrayList<NewsTypeEntity>()

                        it.data.forEach {
                            if(!it.name.trim().equals("")){
                                Log.i("===type",it.toString()+"dd")
                                db.homeTab.addTab(db.homeTab.newTab().setText(it.name))
                                list.add(it)

                            }
                        }
                        if(list.size!=0){
                            vm2.channel.send(NewsIntent.getNews(1,list.get(0).id))
                        }
                    }
                    is NewsTypeState.onError->
                        Log.i("===",it.msg)
                    else -> {}
                }
            }
        }
        //新闻列表数据
        lifecycleScope.launch {
            vm2.newsState.collect{
                when(it){
                    is NewsState.onSucess->
                    {
                        Log.i("===",it.data.toString())
                        newsAdapter.addData(it.data)
//                        newsAdapter.notifyDataSetChanged()
                        if(it.data.size==0){
                            return@collect
                        }
                        val arrayList = ArrayList<String>()
                        for (i in 0..4){
                            arrayList.add(it.data[i].imgurl)
                        }
                        db.homeBanner.setImages(arrayList)
                        db.homeBanner.setImageLoader(object : ImageLoader() {
                            override fun displayImage(
                                context: Context?,
                                path: Any?,
                                imageView: ImageView?
                            ) {
                                GlideUtils.loadRoundImage(context!!,path.toString(),imageView!!)
                            }
                        })
                        db.homeBanner.start()
                    }
                    is NewsState.onError->
                        Log.i("===",it.msg)
                    else -> {}
                }
            }
        }




        lifecycleScope.launch {
            vm.channel.send(NewsTypeIntent.getNewsType)

        }

        return db.root
    }
}